import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'index_state.dart';
import '../core/global_service/global_service.dart';
import 'home/home_view.dart';
import 'my/my_view.dart';

import 'package:test_app/core/base/base/base_logic.dart';

class IndexController extends BaseLogic {
  final IndexState indexState = IndexState();
  final globalService = Get.find<GlobalService>();

  final List<Widget> pageList = [
    const HomeView(),
    const MyView(),
  ];

  @override
  void onInit() {
    super.onInit();
    debugPrint('IndexController initialized');
    init();
  }

  void init() {
    indexState.pageController = PageController(
      initialPage: globalService.tabIndex.value,
    );

    tabBarClick(globalService.tabIndex.value);
  }

  /// 底部导航栏点击
  void tabBarClick(int index) {
    indexState.isAnimating.value = true;
    globalService.setTabIndex(index);
    setPageView(index);
  }


  void pageViewChange(int index) {
    if (!indexState.isAnimating.value) {
      globalService.setTabIndex(index);
      indexState.isAnimating.value = false;
      return;
    }

    if (globalService.tabIndex.value == index && indexState.isAnimating.value) {
      globalService.setTabIndex(index);
      indexState.isAnimating.value = false;
    }
  }

  /// 设置页面
  void setPageView(int index) {
    // 检查控制器是否已绑定到 PageView
    if (indexState.pageController.hasClients) {
      // 已绑定，直接执行动画
      indexState.pageController.animateToPage(
        index,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    } else {
      // 未绑定，延迟到下一帧再尝试（给 PageView 构建时间）
      WidgetsBinding.instance.addPostFrameCallback((_) {
        // 再次检查，避免重复延迟
        if (indexState.pageController.hasClients) {
          indexState.pageController.animateToPage(
            index,
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeInOut,
          );
        }
      });
    }
  }

  @override
  void onClose() {
    indexState.pageController.dispose();
    super.onClose();
  }

}
